package com.bawei.music.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.widget.RemoteViews;

import com.bawei.music.Mode;
import com.bawei.music.R;
import com.bawei.music.Song;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.RequiresApi;

public class MusicService extends Service {
    //3:音乐播放器需要的成员变量
    private MediaPlayer mMediaPlayer = new MediaPlayer();
    private List<Song> songs = new ArrayList();
    private Mode mode = Mode.ORDER;//播放模式 默认顺序
    private int currentPosition = 0;//当前播放音乐下标
    public MusicService() {
    }

    //发送一个前台服务：通知的形式存在
    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint("RemoteViewLayout")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //自定义view
        RemoteViews remoteViews = new RemoteViews(getPackageName(),R.layout.noti);
        remoteViews.setTextViewText(R.id.tv_name,"句号");
        //点击事件：发送广播
        {
            Intent intent1 = new Intent();
            intent1.setAction("com.bawei.music.next");
            remoteViews.setOnClickPendingIntent(R.id.iv_next, PendingIntent.getBroadcast(this,101,intent1,PendingIntent.FLAG_UPDATE_CURRENT));
        }
        {
            Intent intent1 = new Intent();
            intent1.setAction("com.bawei.music.pre");
            remoteViews.setOnClickPendingIntent(R.id.iv_pre, PendingIntent.getBroadcast(this,101,intent1,PendingIntent.FLAG_UPDATE_CURRENT));
        }
        {
            Intent intent1 = new Intent();
            intent1.setAction("com.bawei.music.startOrPause");
            remoteViews.setOnClickPendingIntent(R.id.iv_play, PendingIntent.getBroadcast(this,101,intent1,PendingIntent.FLAG_UPDATE_CURRENT));
        }

        //通知对象
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);//设置小图标，千万不要省略
        builder.setCustomContentView(remoteViews);//自定义通知布局
        Notification notification = builder.build();
        //前台服务
        startForeground(1,notification);
        return super.onStartCommand(intent, flags, startId);
    }

    //2：返回音乐代理对象
    @Override
    public IBinder onBind(Intent intent) {
        return new MusicBinder();
    }
    //1:音乐代理对象 4：将音乐所有方法移动到此处
    class MusicBinder extends Binder{
        /**
         * 设置音乐集合列表
         */
        public void setList(List<Song> list) {
           songs.clear();
           songs.addAll(list);
        }
        /**
         * 切换播放模式
         */
        public void setMode(Mode mode){
            MusicService.this.mode = mode;
        }

        /**
         * 切歌
         */
        public void play(){
            if(mMediaPlayer == null){
                mMediaPlayer = new MediaPlayer();
            }
            try {
                mMediaPlayer.reset();//注意：设置新资源前一定要记得重制
                mMediaPlayer.setDataSource(songs.get(currentPosition).getData());//设置歌曲的资源
                mMediaPlayer.prepareAsync();//异步准备
                //准备监听
                mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {//准备监听
                    @Override
                    public void onPrepared(MediaPlayer mp) {//准备完成
                        mMediaPlayer.start();
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /**
         * 继续播放或暂停
         */
        public void startOrPause(){
            if(mMediaPlayer != null){
                if(mMediaPlayer.isPlaying()){//判断是否正在播放
                    mMediaPlayer.pause();
                }else{
                    mMediaPlayer.start();
                }
            }
        }

        /**
         * 下一首 顺序：下标+1 随机：随机值 单曲：下标不变
         */
        public void next(){
            if(mode == Mode.ORDER){//顺序播放
                if(currentPosition == songs.size()-1){//是否为最后一首歌
                    currentPosition = 0;
                }else{
                    currentPosition++;
                }
            }else if(mode == Mode.RANDOM){//随机播放 0- 长度-1
                currentPosition = (int) (Math.random()*songs.size());
            }
            play();//切换歌曲
        }

        /**
         * 上一首 顺序：下标-1 随机：随机值 单曲：下标不变
         */
        public void pre(){
            if(mode == Mode.ORDER){//
                if(currentPosition == 0){//如果是第一首
                    currentPosition = songs.size()-1;
                }else{
                    currentPosition--;
                }
            }else if(mode == Mode.RANDOM){//随机播放 0- 长度-1
                currentPosition = (int) (Math.random()*songs.size());
            }
            play();//切换歌曲
        }

        /**
         * 快进
         */
        public void quick(){
            if(mMediaPlayer != null){
                //获得当前音乐播放进度
                int currentPosition = mMediaPlayer.getCurrentPosition();
                //进度+5秒
                currentPosition+=5*1000;
                //设置最新的进度
                mMediaPlayer.seekTo(currentPosition);

            }

        }

        /**
         * 快退
         */
        public void back(){
            if(mMediaPlayer != null){
                //获得当前音乐播放进度
                int currentPosition = mMediaPlayer.getCurrentPosition();
                //进度+5秒
                currentPosition-=5*1000;
                //设置最新的进度
                mMediaPlayer.seekTo(currentPosition);

            }
        }

        /**
         * 获得当前播放时间  00:00
         */
        public String getCurrentTime(){
            if(mMediaPlayer != null){
                int currentPosition = mMediaPlayer.getCurrentPosition();//当前进度，毫秒值为单位
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");//格式化 00:00
                return simpleDateFormat.format(currentPosition);
            }
            return "00:00";
        }

        /**
         * 获得总时间  00:00
         */
        public String getDurationTime(){
            if(mMediaPlayer != null){
                int currentPosition = mMediaPlayer.getDuration();//总时间，毫秒值为单位
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("mm:ss");//格式化 00:00
                return simpleDateFormat.format(currentPosition);
            }
            return "00:00";
        }

        /**
         * 获得进度的百分比 0-100     当前进度*100/总时长
         * @return
         */
        public int getProgress(){
            if(mMediaPlayer != null){
                return mMediaPlayer.getCurrentPosition()*100/mMediaPlayer.getDuration();
            }
            return 0;
        }

        /**
         * 根据进度音乐播放到指定进度
         * @param progress 0-100
         */
        public void seekTo(int progress){
            if(mMediaPlayer != null){
                int i = progress * mMediaPlayer.getDuration() / 100;
                mMediaPlayer.seekTo(i);
            }
        }

        /**
         * 释放音乐资源
         */
        public void release(){
            if(mMediaPlayer != null){
                mMediaPlayer.release();//释放音乐的资源
                mMediaPlayer = null;
            }
        }

    }
}